package top.kaoshanji.q1ch07c;

import top.kaoshanji.y1constant.FileConstant;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import java.util.concurrent.TimeUnit;

/**
 * 代码清单-q1ch07c-361页a：基本的文件加锁示例
 * author kaoshanji
 * ^_^
 * create time 2025/3/12 19:19
 */
public class FileLocking {

    static String pathStr = FileConstant.LOCAL_ROOT_PATH.concat("q1ch07c361页a\\file.txt");

    public static void main(String[] args) {

        try (FileOutputStream fos = new FileOutputStream(pathStr);
             FileLock fl = fos.getChannel().tryLock()){

            if (fl != null) {
                System.out.println("Locked File");

                TimeUnit.MILLISECONDS.sleep(100);

                fl.release();
                System.out.println("Released Lock");
            }

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }


    }

}
